<template>
  <el-container class="customer-container">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="logo">
        <el-icon class="logo-icon"><Menu /></el-icon>
        <span class="logo-text">动态字段管理系统</span>
      </div>
      <div class="user-info">
        <el-avatar icon="User" size="small"></el-avatar>
        <span class="user-name">管理员</span>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-container>
      <!-- 侧边菜单 -->
      <el-aside width="200px" class="aside">
        <el-menu default-active="2" class="menu" @select="handleMenuSelect">
          <el-menu-item index="1">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="2">
            <el-icon><User /></el-icon>
            <span>客户管理</span>
          </el-menu-item>
          <el-menu-item index="3">
            <el-icon><ShoppingCart /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="4">
            <el-icon><Setting /></el-icon>
            <span>字段配置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 客户管理内容 -->
      <el-main class="main-content">
        <el-card class="content-card">
          <div slot="header" class="card-header">
            <span>客户管理</span>
            <el-button type="primary" icon="Plus" @click="openAddDialog"
              >新增客户</el-button
            >
          </div>

          <!-- 动态查询表单 -->
          <dynamic-query-form
            :fields="queryFields"
            @query="handleQuery"
            @reset="handleReset"
          ></dynamic-query-form>

          <!-- 表格显示状态提示 -->
          <div
            v-if="
              !loading && tableData.length === 0 && tableFields.length === 0
            "
            class="empty-hint"
          >
            <el-empty
              description="未获取到表格字段配置，请先配置字段"
            ></el-empty>
          </div>

          <div
            v-if="!loading && tableData.length === 0 && tableFields.length > 0"
            class="empty-hint"
          >
            <el-empty description="暂无客户数据"></el-empty>
          </div>

          <!-- 客户数据表格 -->
          <el-table
            v-if="tableFields.length > 0"
            :data="tableData"
            border
            stripe
            style="width: 100%; margin-top: 16px"
            size="small"
            v-loading="loading"
          >
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            ></el-table-column>

            <!-- 修复：移除HTML注释，解决插槽冲突 -->
            <el-table-column
              v-for="field in tableFields"
              :key="`col-${field.fieldName}`"
              :label="field.displayName || '未知字段'"
              :align="field.fieldType === 'number' ? 'right' : 'left'"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <!-- 基础字段渲染 -->
                <template
                  v-if="
                    field.isBaseField &&
                    scope.row[field.fieldName] !== undefined
                  "
                >
                  <template
                    v-if="
                      field.formComponentType === 'select' &&
                      field.options?.options
                    "
                  >
                    {{
                      getOptionLabel(
                        field.options.options,
                        scope.row[field.fieldName]
                      )
                    }}
                  </template>
                  <template v-else-if="field.fieldType === 'date'">
                    {{ formatDate(scope.row[field.fieldName]) }}
                  </template>
                  <template v-else-if="field.fieldType === 'number'">
                    {{ formatNumber(scope.row[field.fieldName]) }}
                  </template>
                  <template v-else-if="field.fieldType === 'boolean'">
                    {{ scope.row[field.fieldName] ? "是" : "否" }}
                  </template>
                  <template v-else>
                    {{ scope.row[field.fieldName] || "-" }}
                  </template>
                </template>

                <!-- 扩展字段渲染 -->
                <template v-else-if="!field.isBaseField">
                  <template
                    v-if="
                      scope.row.extFields &&
                      scope.row.extFields[field.systemFieldName] !== undefined
                    "
                  >
                    <template
                      v-if="
                        field.formComponentType === 'select' &&
                        field.options?.options
                      "
                    >
                      {{
                        getOptionLabel(
                          field.options.options,
                          scope.row.extFields[field.systemFieldName]
                        )
                      }}
                    </template>
                    <template v-else-if="field.fieldType === 'boolean'">
                      {{
                        scope.row.extFields[field.systemFieldName] ? "是" : "否"
                      }}
                    </template>
                    <template v-else-if="field.fieldType === 'date'">
                      {{
                        formatDate(scope.row.extFields[field.systemFieldName])
                      }}
                    </template>
                    <template v-else-if="field.fieldType === 'number'">
                      {{
                        formatNumber(scope.row.extFields[field.systemFieldName])
                      }}
                    </template>
                    <template v-else>
                      {{ scope.row.extFields[field.systemFieldName] || "-" }}
                    </template>
                  </template>
                  <template v-else>-</template>
                </template>

                <!-- 字段不存在时显示 -->
                <template v-else>-</template>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  danger
                  @click="handleDelete(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="tableFields.length > 0 && total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 16px; text-align: right"
          ></el-pagination>
        </el-card>
      </el-main>
    </el-container>
  </el-container>

  <!-- 新增/编辑弹窗 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="70%"
    destroy-on-close
  >
    <dynamic-form
      :fields="allFields"
      :initial-data="formData"
      :module-id="moduleId"
      @submit="handleFormSubmit"
      @cancel="dialogVisible = false"
    ></dynamic-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading, ElEmpty } from "element-plus";
import DynamicQueryForm from "../components/DynamicQueryForm.vue";
import DynamicForm from "../components/DynamicForm.vue";
import { formatDate, formatNumber, getOptionLabel } from "../utils/format";
import { getFieldsByModuleId } from "../api/field";
import {
  queryCustomer,
  getCustomer,
  saveCustomer,
  deleteCustomer,
} from "../api/customer";
import {
  House,
  User,
  ShoppingCart,
  Setting,
  Menu,
  Plus,
} from "@element-plus/icons-vue";

const router = useRouter();
const moduleId = 1; // 客户管理模块ID

// 状态管理
const loading = ref(false);
const allFields = ref([]); // 所有字段配置
const tableData = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 弹窗状态
const dialogVisible = ref(false);
const dialogTitle = ref("新增客户");
const formData = ref({});

// 可查询字段
const queryFields = computed(() => {
  if (!Array.isArray(allFields.value)) return [];
  return allFields.value
    .filter((field) => field.isQueryable === true)
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
});

// 表格字段
const tableFields = computed(() => {
  if (!Array.isArray(allFields.value)) {
    console.warn("表格字段配置不是数组，无法渲染表格");
    return [];
  }

  // 筛选出需要在表格显示的字段
  const validFields = allFields.value.filter((field) => {
    return (
      field.isTableDisplay === true &&
      field.fieldName && // 确保字段名存在
      field.displayName
    ); // 确保显示名存在
  });

  // 按排序号排序
  const sortedFields = validFields.sort(
    (a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)
  );

  // 调试：打印表格字段
  console.log(
    "表格显示字段:",
    sortedFields.map((f) => ({
      fieldName: f.fieldName,
      displayName: f.displayName,
      isTableDisplay: f.isTableDisplay,
    }))
  );

  return sortedFields;
});

// 菜单选择事件
const handleMenuSelect = (index) => {
  switch (index) {
    case "1":
      router.push("/");
      break;
    case "2":
      router.push("/customer");
      break;
    case "3":
      router.push("/order");
      break;
    case "4":
      router.push("/field-config");
      break;
  }
};

// 初始化页面
const init = async () => {
  const loadingInstance = ElLoading.service({ text: "加载中..." });
  try {
    // 获取字段配置
    const fieldsRes = await getFieldsByModuleId(moduleId);
    allFields.value = Array.isArray(fieldsRes.data?.data)
      ? fieldsRes.data.data
      : Array.isArray(fieldsRes.data)
      ? fieldsRes.data
      : [];

    console.log("所有字段配置:", allFields.value);

    // 初始查询
    await handleQuery([]);
  } catch (error) {
    ElMessage.error(
      "初始化失败：" + (error.response?.data?.message || error.message)
    );
    console.error("初始化错误:", error);
    allFields.value = [];
  } finally {
    loadingInstance.close();
  }
};

// 处理查询
const handleQuery = async (params) => {
  loading.value = true;
  try {
    const res = await queryCustomer(
      moduleId,
      params,
      pageNum.value,
      pageSize.value
    );
    const responseData = res.data?.data || res.data || {};

    // 严格校验数据格式
    tableData.value = Array.isArray(responseData.records)
      ? responseData.records
      : [];
    total.value = Number(responseData.total) || 0;

    console.log("表格数据加载完成:", {
      total: total.value,
      records: tableData.value.length,
      params,
    });
  } catch (error) {
    ElMessage.error(
      "查询失败：" + (error.response?.data?.message || error.message)
    );
    console.error("查询错误:", error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 重置查询
const handleReset = () => {
  pageNum.value = 1;
  handleQuery([]);
};

// 新增客户
const openAddDialog = () => {
  dialogTitle.value = "新增客户";
  formData.value = { moduleId, extFields: {} };
  dialogVisible.value = true;
};

// 编辑客户
const handleEdit = async (row) => {
  const loadingInstance = ElLoading.service({ text: "加载中..." });
  try {
    const res = await getCustomer(row.id);
    const customer = res.data?.data || res.data || {};

    const extFields = {};
    allFields.value.forEach((field) => {
      if (
        !field.isBaseField &&
        customer.extFields?.[field.systemFieldName] != null
      ) {
        extFields[field.fieldName] = customer.extFields[field.systemFieldName];
      }
    });

    formData.value = { ...customer, extFields };
    dialogTitle.value = "编辑客户";
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error(
      "加载失败：" + (error.response?.data?.message || error.message)
    );
  } finally {
    loadingInstance.close();
  }
};

// 删除客户
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除这条客户数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteCustomer(id);
      ElMessage.success("删除成功");
      handleQuery([]);
    } catch (error) {
      ElMessage.error(
        "删除失败：" + (error.response?.data?.message || error.message)
      );
    }
  });
};

// 提交表单
const handleFormSubmit = async (data) => {
  const loadingInstance = ElLoading.service({ text: "保存中..." });
  try {
    const extFields = {};
    allFields.value.forEach((field) => {
      if (!field.isBaseField && data.extFields?.[field.fieldName] != null) {
        extFields[field.systemFieldName] = data.extFields[field.fieldName];
      }
    });

    await saveCustomer({ ...data, extFields });
    ElMessage.success(data.id ? "编辑成功" : "新增成功");
    dialogVisible.value = false;
    handleQuery([]);
  } catch (error) {
    ElMessage.error(
      "保存失败：" + (error.response?.data?.message || error.message)
    );
  } finally {
    loadingInstance.close();
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  pageNum.value = 1;
  handleQuery([]);
};

const handleCurrentChange = (page) => {
  pageNum.value = page;
  handleQuery([]);
};

// 监听表格字段变化
watch(
  tableFields,
  (newVal) => {
    console.log("表格字段变化，当前字段数量:", newVal.length);
  },
  { deep: true }
);

// 监听表格数据变化
watch(
  tableData,
  (newVal) => {
    console.log("表格数据变化，当前记录数:", newVal.length);
  },
  { deep: true }
);

onMounted(() => {
  init();
});
</script>

<style scoped>
.customer-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background: #165dff;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
}
.logo {
  display: flex;
  align-items: center;
}
.logo-icon {
  font-size: 24px;
  margin-right: 8px;
}
.logo-text {
  font-size: 18px;
  font-weight: 500;
}
.user-info {
  display: flex;
  align-items: center;
}
.user-name {
  margin-left: 8px;
  font-size: 14px;
}
.aside {
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
}
.menu {
  border-right: none;
}
.main-content {
  background: #f5f7fa;
  padding: 24px;
  overflow-y: auto;
}
.content-card {
  height: calc(100% - 24px);
  display: flex;
  flex-direction: column;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.empty-hint {
  margin: 40px 0;
  text-align: center;
}
</style>
